﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LibMinecraft.Server;
using LibMinecraft.Model.Packets;
using LibMinecraft.Model;

namespace PartyCraftServer.Commands
{
    public class HelpCommand : Command
    {
        public override bool RequiresOp
        {
            get { return false; }
        }

        public override string DefaultCommand
        {
            get { return "help"; }
        }

        public override string Documentation
        {
            get { return "The help command provides documentation to other commands.\nUsage: /help [command] (page)\n" + 
                "The format for usage is generally as follows:\n/command [required] (optional)\nView available commands with /cmd"; }
        }

        public override void ExecuteCommand(RemoteClient client, params string[] parameters)
        {
            if (parameters.Length == 0)
            {
                parameters = new string[] { "help" };
            }
            if (parameters.Length > 2)
            {
                client.SendChat(ChatColor.Red + "Invalid parameters.  Use /help [command] (page)");
                return;
            }
            int pageNum = 1;
            if (parameters.Length == 2)
            {
                if (!int.TryParse(parameters[1], out pageNum))
                {
                    client.SendChat(ChatColor.Red + "Invalid parameters.  Use /help [command] (page)");
                    return;
                }
            }
            pageNum--;

            foreach (var t in AppDomain.CurrentDomain.GetAssemblies().ToArray()
                .SelectMany(s => s.GetTypes())
                .Where(p => typeof(Command).IsAssignableFrom(p) && p != typeof(Command)))
            {
                Command c = (Command)Activator.CreateInstance(t);
                string[] aliases = new string[0];

                if (PartyCraft.Settings.ContainsKey("command.alias." + c.DefaultCommand))
                    aliases = PartyCraft.Settings["command.alias." + c.DefaultCommand].Replace(" ", "").Split(',');
                if (c.DefaultCommand.ToLower() == parameters[0].ToLower() ||
                    aliases.Contains(parameters[0].ToLower()))
                {
                    string[] lines = c.Documentation.Replace("\r", "").Split('\n');
                    client.SendChat(ChatColor.Blue + "Documentation for " + c.DefaultCommand +
                        " (" + (pageNum + 1) + "/" + (int)Math.Ceiling((double)lines.Length / 5d) + "):");
                    foreach (string l in lines.Skip(pageNum * 5).Take(5))
                        client.SendChat(ChatColor.Gray + l);
                    return;
                }
            }
            client.SendChat(ChatColor.Red + "Command not found!");
        }
    }
}
